import axios from 'axios'
import { apiRequest } from './request'

const API_CONFIG = {
  READ_API: import.meta.env.VITE_SHEEP_BREEDING_READ_API || 'http://39.96.200.62:8411',
  WRITE_API: import.meta.env.VITE_SHEEP_BREEDING_WRITE_API || 'http://39.96.200.62:8511',
  ENDPOINTS: {
    LIST: '/api/EweWeaning/list',
    CREATE: '/api/EweWeaning/create',
    UPDATE: '/api/EweWeaning/update',
    DELETE: '/api/EweWeaning/delete',
    DETAIL: '/api/EweWeaning',
  }
}

const readApi = axios.create({
  baseURL: API_CONFIG.READ_API,
  timeout: 10000
})
const writeApi = axios.create({
  baseURL: API_CONFIG.WRITE_API,
  timeout: 10000
})

readApi.interceptors.request.use(config => {
  const token = localStorage.getItem('Token') || localStorage.getItem('token')
  if (token && config.headers) {
    config.headers.Authorization = `Bearer ${token}`
  }
  return config
})
writeApi.interceptors.request.use(config => {
  const token = localStorage.getItem('Token') || localStorage.getItem('token')
  if (token && config.headers) {
    config.headers.Authorization = `Bearer ${token}`
  }
  return config
})

export function getEweWeaningList(params: any) {
  return readApi.get(API_CONFIG.ENDPOINTS.LIST, { params })
}

export function addEweWeaning(data: any) {
  return writeApi.post(API_CONFIG.ENDPOINTS.CREATE, data)
}

export function updateEweWeaning(id: number, data: any) {
  return writeApi.post(`${API_CONFIG.ENDPOINTS.UPDATE}/${id}`, data)
}

export function deleteEweWeaning(id: number) {
  return writeApi.post(`${API_CONFIG.ENDPOINTS.DELETE}/${id}`)
}

export function getEweWeaningDetail(id: number) {
  return readApi.get(`${API_CONFIG.ENDPOINTS.DETAIL}/${id}`)
}

// 新增断奶记录
// data: 断奶记录表单对象
export function createEweWeaning(data: any) {
  // 这里baseURL建议用环境变量或代理，演示用写死
  return apiRequest({
    url: '/EweWeaning/create',
    method: 'post',
    data,
    baseURL: 'http://39.96.200.62:8511' // 适配本地开发，后续可用.env变量或代理
  })
}
